//
//  DBHelper.m
//  OrderManager
//
//  Created by System Administrator on 2009/3/2.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//
// 資料庫輔助物件

#import "DBHelper.h"

@implementation DBHelper

@synthesize database;
@synthesize databasePath;
@synthesize afullname;
// 傳回 DBHelper 的 singleton
+ (DBHelper *) newInstance:(NSString *)name andEXT:(NSString *)ext andfullname:(NSString *)fullname
{
	// Singleton
	static DBHelper *theInstance;
	
	@synchronized(self){	// 避免同步存取
		if( !theInstance ){
			
			theInstance =   [[DBHelper alloc] init]    ;
			// 檢查資料庫是否已經存在 Documents 路徑內
			 			
			theInstance.afullname=fullname;
			theInstance.databasePath = [theInstance fullPath];
			NSFileManager *fileManager = [NSFileManager defaultManager];
			BOOL success = [fileManager fileExistsAtPath:theInstance.databasePath];
			// 若已經存在則不用從應用程式的資源檔內拷貝到 Documents
			if( !success ){
				// 取得資料庫在資源裏面的路徑
				NSString *resourcePath= [[NSBundle mainBundle] pathForResource:name ofType:ext]; 	
				[fileManager copyItemAtPath:resourcePath toPath:theInstance.databasePath error:nil];
				//[fileManager release];
			}
			 

			[theInstance openDatabase];
		}
	}
	return theInstance;
}

// 開啓資料庫,若已開啓則傳回 database 實例
- (sqlite3 *) openDatabase
{
	if(!database){
		databasePath =  [self fullPath]  ;
		if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
			 
			return database;
		}else{
			return nil;
		}
	}else{
		return database;
	}
}

// 關閉資料庫
- (void) closeDatabase
{
	if(database){
		//NSLog(@"Shuwdown database ...");
		sqlite3_close(database);
	}
}

// 傳回資料庫路徑
- (NSString *) fullPath
{
	if(!databasePath ){
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
		NSString *docPath = [paths objectAtIndex:0];
	
		// <Home>/Documents/databaseName
		databasePath = [docPath stringByAppendingPathComponent: afullname];
	}
	return databasePath;
}

// 資料總數
- (int) countForSQL:(const char *) sql
{
	sqlite3_stmt *stm;
	int count = 0;
	@try{
		if(sqlite3_prepare_v2(database,sql,-1,&stm,NULL) == SQLITE_OK) {
			if( sqlite3_step(stm)==SQLITE_ROW ){
				count = sqlite3_column_int(stm,0);
			}
		}
	}@catch(id exception){
	}@finally {
		// 釋放敘述
		if( stm!=nil )
			sqlite3_finalize(stm);
	}
	return count;	
}
@end
